package com.key.win.business.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.key.win.base.auth.AuthenticationUtil;
import com.key.win.base.page.MybatisPageServiceTemplate;
import com.key.win.base.util.DateUtils;
import com.key.win.base.util.FilePropertyUtils;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.business.meeting.dao.MtRecordingDao;
import com.key.win.business.meeting.enums.MtRecordingTypeEnum;
import com.key.win.business.meeting.enums.MtTargetEnum;
import com.key.win.business.meeting.model.MtRecording;
import com.key.win.business.meeting.service.MtRecordingService;
import com.key.win.business.meeting.vo.MtRecordingVo;
import com.key.win.common.file.model.FileInfo;
import com.key.win.config.FileServiceFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MtRecordingServiceImpl extends ServiceImpl<MtRecordingDao, MtRecording> implements MtRecordingService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    final static String DEVICE_MONITOR = "dm";
    final static String GROUP_MEETING = "gm";

    @Autowired
    private FileServiceFactory fileServiceFactory;

    @Override
    public PageResult<MtRecording> findMtRecordingByPaged(PageRequest<MtRecording> t) {
        PageResult<MtRecording> pageResult = new PageResult<MtRecording>();
        if (CollectionUtils.isEmpty(AuthenticationUtil.getAllDeviceIds()) && CollectionUtils.isEmpty(AuthenticationUtil.getAllGruopIds())) {
            return pageResult;
        }
        if (t.getT().getTargetType() != null && t.getT().getTargetType() == MtTargetEnum.DEVICE && CollectionUtils.isEmpty(AuthenticationUtil.getDeviceIdsByUserIds(t.getT().getUserIds()))) {
            return pageResult;
        }
        if (t.getT().getTargetType() != null && t.getT().getTargetType() == MtTargetEnum.GROUP && CollectionUtils.isEmpty(AuthenticationUtil.getGropIdsByUserIds(t.getT().getUserIds()))) {
            return pageResult;
        }
        MybatisPageServiceTemplate<MtRecording, MtRecording> query = new MybatisPageServiceTemplate<MtRecording, MtRecording>(this.baseMapper) {
            @Override
            protected AbstractWrapper constructWrapper(MtRecording recording) {
                return buildMtRecordingLambdaQueryWrapper(recording);
            }
        };
        return query.doPagingQuery(t);
    }

    @Override
    public List<MtRecording> findMtRecording(MtRecording recording) {
        List<MtRecording> mtRecordings = new ArrayList<>();
        if (CollectionUtils.isEmpty(AuthenticationUtil.getAllDeviceIds()) && CollectionUtils.isEmpty(AuthenticationUtil.getAllGruopIds())) {
            return mtRecordings;
        }
        if (recording.getTargetType() != null && recording.getTargetType() == MtTargetEnum.DEVICE && CollectionUtils.isEmpty(AuthenticationUtil.getDeviceIdsByUserIds(recording.getUserIds()))) {
            return mtRecordings;
        }
        if (recording.getTargetType() != null && recording.getTargetType() == MtTargetEnum.GROUP && CollectionUtils.isEmpty(AuthenticationUtil.getGropIdsByUserIds(recording.getUserIds()))) {
            return mtRecordings;
        }
        LambdaQueryWrapper<MtRecording> queryWrapper = buildMtRecordingLambdaQueryWrapper(recording);
        return super.list(queryWrapper);
    }

    private LambdaQueryWrapper<MtRecording> buildMtRecordingLambdaQueryWrapper(MtRecording recording) {

        LambdaQueryWrapper<MtRecording> queryWrapper = new LambdaQueryWrapper<>();
        if (recording != null) {
            if (StringUtils.isNotBlank(recording.getTargetName())) {
                queryWrapper.like(MtRecording::getTargetName, recording.getTargetName());
            }
            if (StringUtils.isNotBlank(recording.getName())) {
                queryWrapper.like(MtRecording::getName, recording.getName());
            }
            if (recording.getOrigin() != null) {
                queryWrapper.eq(MtRecording::getOrigin, recording.getOrigin());
            }
            if (recording.getType() != null) {
                queryWrapper.eq(MtRecording::getType, recording.getType());
            }

            if (StringUtils.isNotBlank(recording.getStartDate()) && StringUtils.isNotBlank(recording.getEndDate())) {
                queryWrapper.between(MtRecording::getCreateDate, DateUtils.strToTime(recording.getStartDate()), DateUtils.strToTime(recording.getEndDate()));
            }
            if (!CollectionUtils.isEmpty(recording.getUserIds())) {
                if (recording.getTargetType() != null && recording.getTargetType() == MtTargetEnum.DEVICE) {
                    queryWrapper.in(MtRecording::getTargetId, AuthenticationUtil.getDeviceIdsByUserIds(recording.getUserIds()));
                }
                if (recording.getTargetType() != null && recording.getTargetType() == MtTargetEnum.GROUP) {
                    queryWrapper.in(MtRecording::getTargetId, AuthenticationUtil.getGropIdsByUserIds(recording.getUserIds()));
                }
            }
            if (!CollectionUtils.isEmpty(recording.getDeviceIds())) {
                queryWrapper.in(MtRecording::getTargetId, recording.getDeviceIds());
            }
            if (!CollectionUtils.isEmpty(recording.getGroupIds())) {
                queryWrapper.in(MtRecording::getTargetId, recording.getGroupIds());
            }
            if (recording.getTargetType() != null) {
                queryWrapper.eq(MtRecording::getTargetType, recording.getTargetType());
            }
        }
        return queryWrapper;
    }

    @Override
    public boolean saveMtRecording(MtRecordingVo recording) {
        Date date = new Date(recording.getCreatedAt());
        MtRecording mtRecording = new MtRecording();
        mtRecording.setId(recording.getId());
        mtRecording.setCreateDate(date);
        mtRecording.setUpdateDate(date);
        mtRecording.setTargetId(recording.getTargetId());
        mtRecording.setTargetName(recording.getTargetName());
        mtRecording.setDuration(recording.getDuration());
        mtRecording.setName(recording.getName());
        mtRecording.setObject(recording.getObject());
        mtRecording.setOrigin(recording.getOrigin());
        mtRecording.setResolution(recording.getResolution());
        mtRecording.setSessionId(recording.getSessionId());
        mtRecording.setStatus(recording.getStatus());
        mtRecording.setType(MtRecordingTypeEnum.getMtRecordingTypeEnum(recording));
        mtRecording.setFileId(recording.getId());
        if (mtRecording.getType() != MtRecordingTypeEnum.IMAGE) {
            FileInfo fileInfo = new FileInfo();
            fileInfo.setId(recording.getId());
            if (mtRecording.getTargetType() == MtTargetEnum.DEVICE) {
                fileInfo.setBizType(FilePropertyUtils.getPropertyByUploadBiz(DEVICE_MONITOR));
            } else {
                fileInfo.setBizType(FilePropertyUtils.getPropertyByUploadBiz(GROUP_MEETING));
            }
            fileInfo.setId(recording.getId());
            String url = recording.getUrl();
            fileInfo.setContentType(url.substring(url.lastIndexOf(".") + 1));
            fileInfo.setSize(recording.getSize());
            fileInfo.setPath(url);
            fileInfo.setMd5(recording.getId());
            fileInfo.setCreateDate(date);
            fileInfo.setUpdateDate(date);
            fileServiceFactory.getFileService().save(fileInfo);
        }
        return super.save(mtRecording);
    }

    @Override
    public boolean deleteMtRecording(String id) {
        MtRecording byId = this.getById(id);
        FileInfo f = fileServiceFactory.getFileService().getById(byId.getFileId());
        fileServiceFactory.getFileService().delete(f);
        return super.removeById(id);
    }

    @Override
    public MtRecording getMtRecordingFull(String id) {
        MtRecording byId = this.getById(id);
        byId.setFileInfo(fileServiceFactory.getFileService().getById(byId.getFileId()));
        return byId;
    }
}
